﻿using QbservableCore.Serialization.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Serialization;

namespace QbservableCore.Serialization
{
    [DataContract]
    public class NewArrayInitNode : ExpRepresentationBase
    {
        [DataMember]
        public LightweightSerializableType TypeToken { get; set; }

        [DataMember]
        public ExpRepresentationBase[] Initializers { get; set; }

        protected internal override Expression ToExpression(ExepressionBuilderCache exepressionBuilderCache)
        {
            Expression[] initializers = new Expression[Initializers.Length];
            for (int index = 0; index < initializers.Length; index++)
            {
                initializers[index] = Initializers[index].ToExpression(exepressionBuilderCache);
            }
            Type type = TypeToken.GetType();
            return Expression.NewArrayInit(type, initializers);
        }

        protected override void TraverseChildren(Func<ExpRepresentationBase, ExpRepresentationBase> action)
        {
            TraverseNodes(Initializers, action);
        }

        public override string ToString()
        {
            string initializers = string.Join(", ", (object[])Initializers);
            return string.Format("new [] {{{0}}}", initializers);
        }
    }
}